package com.smartfast4j.manager.modules.schedule.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.smartfast4j.common.bean.R;
import com.smartfast4j.common.controller.BaseController;
import com.smartfast4j.manager.modules.schedule.service.ScheduleJobLogService;
import com.smartfast4j.pojo.schedule.ScheduleJobLog;
import com.smartfast4j.pojo.schedule.ScheduleJobLogExample;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* ScheduleJobLogController
*  由代码生成器生成
*/
@RestController
@RequestMapping("/scheduleJobLog")
public class ScheduleJobLogController extends BaseController {

    @Autowired
    private ScheduleJobLogService scheduleJobLogService;

    /**
     * 根据id批量删除日志数据
     * @param ids 要删除的数据ID，以逗号分隔
     * @return
     */
    @RequestMapping(value = "/delete")
    public R delete(String ids){
        List<Long> idList = new ArrayList<>();
        if(StringUtils.isNotEmpty(ids)){
            String[] idArr = ids.split(",");
            for(String id:idArr){
                idList.add(Long.parseLong(id));
            }
        }
        ScheduleJobLogExample logExample = new ScheduleJobLogExample();
        logExample.createCriteria().andLogIdIn(idList);
        //根据id删除
        scheduleJobLogService.deleteByExample(logExample);
        return R.ok();
    }

    /**
     * 定时任务执行日志列表
     * @param offset
     * @param limit
     * @param jobName
     * @return
     */
    @RequestMapping("/list")
    public R list(Integer offset, Integer limit,String jobName){
        if (offset != null && limit != null) {
            //分页查询
            PageHelper.offsetPage(offset, limit);
        }
        ScheduleJobLogExample example = new ScheduleJobLogExample();
        ScheduleJobLogExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotEmpty(jobName)){
            criteria.andJobNameLike("%"+jobName+"%");
        }
        example.setOrderByClause("create_time desc");
        //只有紧跟在 PageHelper.startPage 方法后的第一个 MyBatis 的查询(select)方法会被分页。
        List<ScheduleJobLog> scheduleJobLogList = scheduleJobLogService.selectByExample(example);
        PageInfo<ScheduleJobLog> pageInfo = new PageInfo<>(scheduleJobLogList);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("total",pageInfo.getTotal());
        dataMap.put("rows", pageInfo.getList());
        //服务端分页，返回的结果必须包含total、rows两个参数。漏写或错写都会导致表格无法显示数据。
        return R.ok(dataMap);
    }
}
